var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('sensors_data.db');

var id_sensor_temperature = 8991615;

exports.lastOne = function(req, res){


	var retour = {id_sensor: id_sensor_temperature};

	db.get('SELECT date, data FROM data WHERE id_sensor = ?', [id_sensor_temperature], function(err, row) {
		if(row != undefined)
		{
		  retour['date'] = row.date;
		  retour['value']  = row.data;
		}
		else
		{
		  retour['error'] = 'Error, could not fetch temperature data...';
		  console.log(err);
		}
		res.end(JSON.stringify(retour));
	});
};

exports.last24h = function(req, res){


	var retour = {id_sensor: id_sensor_temperature, data:[]};
	var date24hBefore = new Date((new Date()).getTime()-86400000);

	db.each('SELECT date, data FROM data WHERE id_sensor = ? AND date >= ?', [id_sensor_temperature, date24hBefore.toISOString()], function(err, row) {
		if(row != undefined)
		{
			retour['data'].push({'date': row.date, 'value': row.data});
		}
		else
		 	console.log(err);
	},
	function() // onComplete
	{
		res.end(JSON.stringify(retour));
	});
};